<template>
  <div class="report-form-content">
    <el-form class="my-form"
             ref="objForm"
             :model="obj"
             :rules="rules"
             label-position="right"
             label-width="auto"
             label-suffix="："
             :disabled="oper === 'view' || oper === 'supplement'">
      <div class="tabs-form-head">
        <span>合同借阅</span>
        <div class="">
          <el-button type="primary" plain @click="returnBtn">取消</el-button>
          <el-button type="primary" @click="handleSubmit">申请借阅</el-button>
        </div>
      </div>
      <el-divider border-style="dashed" />
      <el-row :gutter="20">
        <el-col :sm="24" :lg="24" style="padding-left: 20px">
          <el-card class="update-log">
            <div class="report-form-list-content">
              <el-form-item label="合同名称">
                <span v-if="contractInitial">{{ contractInitial.name }}</span>
              </el-form-item>
            </div>
            <div class="report-form-list-content">
              <el-form-item label="合同负责人" v-if="contractInitial">
                <LabelTag :foreignList="userList" :foreignIds="contractInitial.userId" :foreignLabel="'name'" />
              </el-form-item>
            </div>
            <div class="report-form-list-content">
              <el-form-item label="借阅人" prop="borrowUserId">
                <User v-model="obj.borrowUserId" keyName="id" keyShow="name" placeholder="借阅人" title="用户查询" />
              </el-form-item>
            </div>
            <div class="report-form-list-content">
              <el-form-item label="借阅人部门" prop="borrowDepartmentId">
                <Organization v-model="obj.borrowDepartmentId" keyName="id" keyShow="organizationName" placeholder="借阅人部门" title="部门查询" />
              </el-form-item>
            </div>
            <div class="report-form-list-content">
              <el-form-item label="借阅类型" prop="borrowType">
                <el-radio-group v-model="obj.borrowType">
                  <el-radio-button v-for="item in getDictList('ContractInitialBorrowType')" :key="item.key" :label="item.key">{{ `${item.key} - ${item.value}` }}</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </div>
            <div class="report-form-list-content-1">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="obj.remark" :autosize="{ minRows: 2, maxRows: 5}" type="textarea" />
              </el-form-item>
            </div>

          </el-card>
        </el-col>
      </el-row>
      <div class="tabs-form-head">
        <span>合同借阅记录</span>
      </div>
      <el-card class="update-log">
        <el-table :data="contractInitialBorrowList"
                  style="width: 100%;
          margin-top: 20px"
                  row-key="id"
                  border
                  default-expand-all>
          <el-table-column align="center" type="index" label="序号" width="60px" />
          <el-table-column align="center" label="合同编码" prop="code" sortable show-overflow-tooltip>
            <template v-slot="{row}">{{ contractInitial.code }}</template>
          </el-table-column>
          <el-table-column align="center" label="合同名称" prop="name" sortable show-overflow-tooltip>
            <template v-slot="{row}">{{ contractInitial.name }}</template>
          </el-table-column>
          <el-table-column align="center" label="借阅类型" prop="borrowType" sortable show-overflow-tooltip>
            <template v-slot="{row}">{{ row.borrowType === '1' ? '纸质' : '电子'  }}</template>
          </el-table-column>
          <el-table-column align="center" label="借阅人" prop="borrowUserId" sortable show-overflow-tooltip>
            <template v-slot="{row}">{{ showIdLabel(userList, row.borrowUserId, 'name') }}</template>
          </el-table-column>
          <el-table-column align="center" label="借阅状态" prop="state" sortable show-overflow-tooltip>
            <template v-slot="{row}">
              <EnumTag :enum-list="getEnumList('ContractInitialBorrowState')" :enum-key="row.state" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="备注" prop="borrowUserId" sortable show-overflow-tooltip>
            <template v-slot="{row}">{{ row.remark }}</template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>
    <selectApprove v-model:itemsVisible="dialogApproveVisible" @close="dialogApproveVisible = false" :business="'3006'" :businessId="obj.id" @doSubmit="doSubmit" />
  </div>
</template>
<script setup>
import {getCurrentInstance, ref} from 'vue'
import {doGet, doPost} from "@/config/http";
import {
  svc,
  showIdLabel,
  getListPageSize,
  alertErrorMsg,
  getDictList,
  getEnumList,
  notifySuccess,
  customValidator
} from "@/config/common";
import { useRoute, useRouter } from 'vue-router'
import Organization from "@/views/components/base/selectOrganization.vue";
import User from "@/views/components/base/selectUser.vue";
import selectApprove from "@/views/components/base/selectApprove.vue";
import initListStore from '@/store/modules/initList'

const router = useRouter()
const route = useRoute()

const { proxy: ctx } = getCurrentInstance();

let objForm = ref(null)
let dialogApproveVisible = ref(false)
const oper = ref(route.query.oper)

let obj = ref({
  contractInitialId: route.query.id, // 合同ID
  batch: null, // 批次号
  borrowUserId: null, // 借阅人
  borrowDepartmentId: null, // 借阅人部门
  borrowType: null, // 借阅类型
  state: null, // 借阅状态
  borrowToken: null, // 借阅凭据
  borrowAttachmentId: null, // 借阅签字附件
  downloadTimes: null, // 电子档下载次数
  returnTime: null, // 归还时间
  remark: null, // 备注
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
})

let contractInitial = ref(null)
let contractInitialBorrowList = ref([])

// let contractTypeList = initListStore().contractTypeList // 合同类型
// let contractCooperationList = initListStore().contractCooperationList // 往来单位
// let contractFeetypeList = initListStore().contractFeetypeList // 合同费用类型
// let contractTemplateList = initListStore().contractTemplateList // 合同模版
// let bankList = initListStore().bankList // 银行
let userList = initListStore().userList // 用户
// let governmentList = initListStore().governmentList //  政府单位
// let organizationList = initListStore().organizationList // 部门
// let contractSignerList = initListStore().contractSignerList // 签订人
// let contractFiletypeList = initListStore().contractFiletypeList // 合同附件类型

const rules = {
  contractInitialId: [{ required: true, validator: customValidator, min: 1, max: 20, label: '合同ID', trigger: ['blur', 'change'] }],
  batch: [{ required: false, validator: customValidator, min: 0, max: 20, label: '批次号', trigger: ['blur', 'change'] }],
  borrowUserId: [{ required: true, validator: customValidator, min: 0, max: 20, label: '借阅人', trigger: ['blur', 'change'] }],
  borrowDepartmentId: [{ required: true, validator: customValidator, min: 0, max: 20, label: '借阅人部门', trigger: ['blur', 'change'] }],
  borrowType: [{ required: true, validator: customValidator, min: 0, max: 1000, label: '借阅类型', trigger: ['blur', 'change'] }],
  state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '借阅状态', trigger: ['blur', 'change'] }],
  borrowToken: [{ required: false, validator: customValidator, min: 0, max: 100, label: '借阅凭据', trigger: ['blur', 'change'] }],
  borrowAttachmentId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '借阅签字附件', trigger: ['blur', 'change'] }],
  downloadTimes: [{ required: false, validator: customValidator, min: 0, max: 20, label: '电子档下载次数', trigger: ['blur', 'change'] }],
  returnTime: [{ required: false, validator: customValidator, min: 0, max: 20, label: '归还时间', trigger: ['blur', 'change'] }],
  remark: [{ required: false, validator: customValidator, min: 0, max: 1000, label: '备注', trigger: ['blur', 'change'] }],
}

// const initList = async () => {
//   let p1 = doGet(svc, '/contract-type/page', {pageSize: getListPageSize()}, false) // 合同类型
//   let p2 = doGet(svc, '/contract-cooperation/page', {pageSize: getListPageSize()}, false) // 往来单位
//   let p3 = doGet(svc, '/contract-feetype/page', {pageSize: getListPageSize()}, false) // 合同费用类型
//   let p4 = doGet(svc, '/contract-template/page', {pageSize: getListPageSize()}, false) // 合同模版
//   let p5 = doGet(svc, '/bank/page', {pageSize: getListPageSize()}, false) // 银行
//   let p6 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false) // 用户
//   let p7 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false) //  政府单位
//   let p8 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false) // 部门
//   let p9 = doGet(svc, '/contract-signer/page', {pageSize: getListPageSize()}, false) // 签订人
//   let p10 = doGet(svc, '/contract-filetype/page', {pageSize: getListPageSize()}, false) // 合同附件类型

//   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6, p7, p8, p9, p10])
//   contractTypeList.value = resArray[0]['records']
//   contractCooperationList.value = resArray[1]['records']
//   contractFeetypeList.value = resArray[2]['records']
//   contractTemplateList.value = resArray[3]['records']
//   bankList.value = resArray[4]['records']
//   userList.value = resArray[5]['records']
//   governmentList.value = resArray[6]['records']
//   organizationList.value = resArray[7]['records']
//   contractSignerList.value = resArray[8]['records']
//   contractFiletypeList.value = resArray[9]['records']
// }
const initObj = async () =>  {
  if (route.query.id) {
    contractInitial.value = await doGet(svc, '/contract-initial/' + route.query.id, {}, false)
    contractInitialBorrowList.value = await doGet(svc, '/contract-initial-borrow/listByField', {field: 'contractInitialId', values: route.query.id}, true)
  }
}

initObj()
// initList()

const handleSubmit = async () => {
  let v = await objForm.value.validate().catch((err)=>{return err})
  if (v !== true) {
    alertErrorMsg('表单验证不通过，请检查数据。')
    return
  }
  dialogApproveVisible.value = true
}

const doSubmit = async (data) => {
  let v = await objForm.value.validate().catch((err)=>{return err})
  if (v !== true) {
    alertErrorMsg('表单验证不通过，请检查数据。')
    return
  }
  let o = {}
  o.oper = 'add'
  o.approveId = data.approveId
  o.approveNodes = data.approveNodes
  o.items = [obj.value]
  doPost(svc, `/customContractInitial/borrowContractInitial/${route.query.id}`, o, true).then(() => {
    notifySuccess('提交成功')
    returnBtn()
  })
}

const returnBtn = () => {
  switch (route.query.kind) {
    case '1':
      ctx.goTargetByName('contractInitial', {});
      break;
    case '2':
      ctx.goTargetByName('contractMain', {})
      break;
  }
}
</script>
<style scoped>
.report-form-content {
  padding: 20px;
}
.update-log {
  width: 100%;
  margin: 30px 0;
}
.tabs-form-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tabs-form-head span {
  font-size: 18px;
  color: #303133;
  font-weight: bold;
}
</style>
